<script lang="ts" setup>
const props = defineProps<{
  title: string
  list: string[]
  modelValue?: string | number
}>()
const emit = defineEmits(['update:modelValue'])
const unfold = ref(false)
const selected = ref(props.modelValue || '')
const options = computed<any[]>(() => [{ label: '不限', value: '' }, ...props.list])
function onSelect(item: any) {
  if (item && typeof item === 'object') {
    selected.value = item.value
  }
  else {
    selected.value = item
  }
}

watch(() => selected.value, (newVal) => {
  if (newVal !== props.modelValue) {
    emit('update:modelValue', selected.value)
  }
})
watch(() => props.modelValue, (newVal) => {
  if (newVal !== selected.value) {
    selected.value = props.modelValue as string | number
  }
})

const contentRef = ref<HTMLElement | null>(null)
const parentRef = ref<HTMLElement | null>(null)
const isOverflowed = ref(false)

function checkOverflow() {
  if (contentRef.value && parentRef.value) {
    isOverflowed.value = contentRef.value.scrollHeight > parentRef.value.clientHeight
  }
}

onMounted(() => {
  checkOverflow()
})

watch(() => props.list, () => {
  nextTick(() => {
    checkOverflow()
  })
}, {
  deep: true,
  immediate: true,
})
</script>

<template>
  <div class="filter-row mb-20px flex flex-1" border="1px solid #E5E5EA">
    <div class="w-120px bg-#EBF7F5 p-2 text-center">
      {{ title }}
    </div>
    <div ref="parentRef" class="custom-style flex flex-1 items-start items-center px-10px py-5px">
      <div
        ref="contentRef"
        flex="~ items-center wrap 1"
        class="overflow-hidden"
        :class="{ 'h-auto': unfold, 'h-30px': !unfold }"
      >
        <span
          v-for="(item, index) in options" :key="index"
          :class="{ active: item?.value === selected || item === selected }"
          class="mb-10px cursor-pointer px-20px line-height-30px"
          @click="onSelect(item)"
        >
          <template v-if="typeof item === 'object'">
            {{ item.label }}
          </template>
          <template v-else>
            <div>
              {{ item }}
            </div>
          </template>
        </span>
      </div>

      <div v-if="isOverflowed" class="w-100px cursor-pointer select-none text-right line-height-30px" @click="unfold = !unfold">
        展开 <i class="i-ri:arrow-drop-down-fill inline-block transition" :style="unfold ? 'transform: rotate(180deg);' : ''" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.active {
  color: #fff;
  background: linear-gradient(159.97deg, rgba(206, 234, 158, 1) -140.78%, #AC8358 89.45%);
  border-radius: 4px;
}
</style>
